using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.SqlClient;
using DevExpress.Xpo.DB;
using DevExpress.Xpo;
using System.Xml;
using DevExpress.Data.Filtering;
using DevExpress.Internal;
using CDMS.Utilities;

namespace CDMS.Utilites
{
    public partial class frmSQLConnector : XtraForm
    {
        string defaultDB = "ServerModeGridProjects";
        string serverParameters = "SQLParameters.xml";
        public frmSQLConnector()
        {
        }
        public frmSQLConnector(string demoString)
        {
            InitializeComponent();
            cbDatabase.Text = defaultDB;
            sbExit.Text += demoString;
            teServer.Text = DbEngineDetector.GetSqlServerInstanceName();
            ShowParameters();

            DevExpress.Skins.Skin currentSkin = DevExpress.Skins.CommonSkins.GetSkin(this.LookAndFeel);
            lbTitle.Appearance.BackColor = currentSkin.Colors.GetColor(DevExpress.Skins.CommonSkins.SkinGroupPanelCaptionTop);
            lbTitle.Appearance.ForeColor = currentSkin.Colors.GetColor(DevExpress.Skins.CommonColors.ControlText);
        }

        void ShowParameters()
        {
            if (!System.IO.File.Exists(serverParameters)) return;
            sbExit.Enabled = true;
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(serverParameters);
            }
            catch { }
            if (doc.DocumentElement.Name == "Parameters")
            {
                string[] prm = doc.DocumentElement.InnerText.Split(new char[] { ';' });
                teServer.Text = prm[0];
                radioGroup1.SelectedIndex = Convert.ToInt32(prm[1]);
                teLogin.Text = prm[2];
                tePassword.Text = prm[3];
            }
        }


        private void radioGroup1_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool disable = radioGroup1.SelectedIndex == 0;
            DisableSQLServerAuthentication(disable);
        }

        void DisableSQLServerAuthentication(bool disable)
        {
            teLogin.Enabled = !disable;
            tePassword.Enabled = !disable;
        }
        public string ConnectionStringParameters
        {
            get
            {
                return string.Format("{0};{1};{2};{3}", teServer.Text, radioGroup1.SelectedIndex, teLogin.Text, tePassword.Text);
            }
        }
        string GetServerConnectionString()
        {
            string connectionString = String.Format("data source={0};integrated security=SSPI", teServer.Text);
            if (radioGroup1.SelectedIndex == 1)
                connectionString = String.Format("data source={0};user id={1};password={2}", teServer.Text, teLogin.Text, tePassword.Text);
            return connectionString;
        }

        public string GetDataBaseConnectionString()
        {
            if (DialogResult == DialogResult.Cancel) return string.Empty;
            string connectionString = GetServerConnectionString();
            return connectionString + ";initial catalog=" + cbDatabase.Text;
        }


        void AddTableNames()
        {
            using (SqlConnection connection = new SqlConnection(GetServerConnectionString()))
            {
                try
                {
                    connection.Open();
                }
                catch
                {
                    XtraMessageBox.Show(ServerModeStrings.failedConnection, ServerModeStrings.failedConnectionCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                using (SqlCommand command = new SqlCommand("select name from master..sysdatabases", connection))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        cbDatabase.Properties.Items.Clear();
                        while (reader.Read())
                        {
                            string name = reader.GetString(0);
                            if ("master;model;tempdb;msdb;pubs".IndexOf(name) < 0)
                                cbDatabase.Properties.Items.Add(name);
                        }
                    }
                }
            }
        }

        private void cbDatabase_QueryPopUp(object sender, CancelEventArgs e)
        {
            AddTableNames();
        }

        private void cbDatabase_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void teServer_EditValueChanged(object sender, EventArgs e)
        {
            cbDatabase.Text = defaultDB;
            cbDatabase.Properties.Items.Clear();
        }

        public static bool CorrectConnection(string serverConnectionString)
        {
            Cursor cur = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            using (SqlConnection connection = new SqlConnection(serverConnectionString))
            {
                try
                {
                    connection.Open();
                    connection.Close();
                }
                catch
                {
                    XtraMessageBox.Show(ServerModeStrings.failedConnection, ServerModeStrings.failedConnectionCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false; ;
                }
                finally
                {
                    Cursor.Current = cur;
                }
            }
            return true;
        }


        private void sbExit_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.No;
            CloseForm();
        }

        void CloseForm()
        {
            if (!CorrectConnection(GetServerConnectionString())) return;
            try
            {
                using (XmlTextWriter tw = new XmlTextWriter(serverParameters, System.Text.Encoding.UTF8))
                {
                    tw.WriteElementString("Parameters", ConnectionStringParameters);
                }
            }
            catch { }
            this.Close();
        }

        private void frmSQLConnector_FormClosing(object sender, FormClosingEventArgs e)
        {
        }
    }
}
